import { defineStore } from 'pinia';
import { ref, reactive, computed } from 'vue';
import router from '@/router';
import { useRoute } from 'vue-router';
import { isString } from 'lodash-es';
import {
  setToken as _setToken,
  getToken,
  removeToken,
} from '@/common/utils/cache/cookies';
import { getCurrentUserInfoApi } from '@/common/apis/users/index.ts';
import { clearRouteParams } from '@/pages/Project/hooks/useModuleState';
import { getProjectPermissionsApi } from '@/common/apis/projectMember/index.ts';
import { clearRouteAddedFlags, resetRouter } from '@/router/guard';

export const useUserStore = defineStore(
  'user',
  () => {
    const route = useRoute();
    const userInfo = ref<any | null>(null);
    const hasShownGiteeNotification = ref(false); // 添加通知显示状态
    const token = ref<string>(getToken() || '');
    // 菜单/基础权限
    const menuPermissions = ref<string[]>([]);
    // 使用一个对象来缓存多个项目的权限，Key是projectId，Value是权限数组，项目权限缓存
    const projectPermissionsCache = reactive<Record<number, string[]>>({});
    // 获取当前项目id
    const currentProjectId = computed(() => {
      return Number(route.params.id);
    });

    // 设置 Token
    const setToken = (value: string) => {
      _setToken(value);
      token.value = value;
    };

    // 登出
    const logout = () => {
      removeToken();
      token.value = '';
      userInfo.value = null;
      menuPermissions.value = [];
      // 遍历缓存对象的所有 key,使用 delete 删除每个属性
      Object.keys(projectPermissionsCache).forEach((key) => {
        delete projectPermissionsCache[key as unknown as number];
      });
      // 清空路由参数，避免重新登录后自动选中之前的API
      clearRouteParams();
      // 清空路由添加标志，确保下次登录时重新添加路由
      clearRouteAddedFlags();
      // 重置路由
      resetRouter();
      router.push({ path: '/login', replace: true });
    };

    // 重置 Token
    const resetToken = () => {
      removeToken();
      token.value = '';
    };

    // 获取用户信息
    const getCurrentUserInfo = async () => {
      try {
        const { data } = await getCurrentUserInfoApi();
        const { id, nickname, username } = data;
        userInfo.value = {
          id,
          nickname,
          username,
        };
      } catch (error) {
        console.error('获取用户信息失败:', error);
      }
    };

    // 获取当前用户信息（同步）
    const getUserInfo = () => {
      return userInfo.value;
    };

    const getProjectPermissions = async (projectId?: number) => {
      // 使用传入的 projectId 或当前路由的 projectId
      const targetProjectId = projectId || currentProjectId.value;

      if (!targetProjectId) {
        console.error('项目ID不能为空');
        return [];
      }

      // 检查用户信息是否存在
      if (!userInfo.value) {
        console.error('用户信息不存在，请先获取用户信息');
        return [];
      }

      // --- 核心缓存逻辑 ---
      // 判断检查当前项目的权限是否已被缓存
      if (projectPermissionsCache[targetProjectId]) {
        return projectPermissionsCache[targetProjectId];
      }
      try {
        const { data } = await getProjectPermissionsApi({
          id: userInfo.value.id,
          projectId: targetProjectId,
        });

        // 将权限数据缓存到对应项目，并提取 code
        projectPermissionsCache[targetProjectId] = data
          ? data.map((item: any) => item.code)
          : [];
        return data || [];
      } catch (error) {
        console.error('获取项目权限失败:', error);
        projectPermissionsCache[targetProjectId] = [];
        return [];
      }
    };

    // 检查用户权限.     // isUnion false 需要所有权限，true 只需要其中一个
    const hasPermission = (
      permission: string | string[],
      type: string = 'project', // 默认是每个项目里面的权限
      isUnion: boolean = false,
      projectId?: number // 新增参数，用于指定项目ID
    ) => {
      if (!permission) {
        return true;
      }
      const _permissions: string[] = (
        isString(permission) ? [permission] : permission
      ) as string[];

      // 使用传入的 projectId 或当前路由的 projectId
      const targetProjectId = projectId || currentProjectId.value;

      const totalPermission =
        type === 'project'
          ? projectPermissionsCache[targetProjectId]
          : menuPermissions.value;
      const permissionsToCheck = totalPermission || []; // 提供默认值
      return isUnion
        ? _permissions.some((code: string) => {
            return permissionsToCheck.includes(code);
          })
        : _permissions.every((code: string) => {
            return permissionsToCheck.includes(code);
          });
    };

    const setGiteeNotificationShown = () => {
      hasShownGiteeNotification.value = true;
    };

    return {
      token,
      userInfo,
      menuPermissions,
      projectPermissionsCache,
      currentProjectId,
      setToken,
      logout,
      resetToken,
      getCurrentUserInfo,
      getUserInfo,
      hasPermission,
      getProjectPermissions,
      setGiteeNotificationShown,
      hasShownGiteeNotification, // 添加这行
    };
  },
  {
    persist: {
      pick: ['userInfo'], // 只持久化 userInfo
    },
  }
);
